package jnpf.engine.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.constant.MsgCode;
import jnpf.engine.FlowTaskApi;
import jnpf.engine.entity.*;
import jnpf.engine.model.flowbefore.FlowBeforeListVO;
import jnpf.engine.model.flowengine.FlowModel;
import jnpf.engine.model.flowengine.FlowPagination;
import jnpf.engine.model.flowengine.shuntjson.nodejson.ChildNodeList;
import jnpf.engine.model.flowtask.FlowTaskListModel;
import jnpf.engine.model.flowtask.PaginationFlowTask;
import jnpf.engine.model.flowtemplate.FlowTemplateCrForm;
import jnpf.engine.model.flowtemplate.FlowTemplateInfoVO;
import jnpf.engine.service.*;
import jnpf.engine.util.FlowNature;
import jnpf.exception.WorkFlowException;
import jnpf.model.FlowWorkListVO;
import jnpf.permission.UserApi;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.model.user.WorkHandoverModel;
import jnpf.util.JsonUtil;
import jnpf.util.ServiceAllUtil;
import jnpf.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/Engine/flowTemplateJson")
public class FlowTempJsonComtroller implements FlowTaskApi {


    @Autowired
    private FlowTaskService flowTaskService;
    @Autowired
    private FlowDelegateService flowDelegateService;
    @Autowired
    private FlowTemplateService flowTemplateService;
    @Autowired
    private FlowTemplateJsonService flowTemplateJsonService;
    @Autowired
    private FlowDynamicService flowDynamicService;
    @Autowired
    private ServiceAllUtil serviceUtil;
    @Autowired
    private   FlowTaskNodeService flowTaskNodeService;
    @Autowired
    private  FlowTaskOperatorService flowTaskOperatorService;
    @Autowired
    private UserApi  userApi;
    @Autowired
    private  FlowTaskMessageService flowTaskMessageService;


    //———————————————流程任务数据——————————

    /**
     * 列表（待我审批）
     *
     * @return
     */
    @Override
    @PostMapping("/GetWaitList")
    public PageListVO getWaitList(@RequestBody PaginationFlowTask pagination) {
        List<FlowTaskListModel> result = flowTaskService.getWaitList(pagination);
        PageListVO pageListVO = new PageListVO();
        pageListVO.setList(result);
        pageListVO.setPagination(JsonUtil.getJsonToBean(pagination,PaginationVO.class));
        return pageListVO;
    }

    /**
     * 列表（我已审批）
     *
     * @return
     */
    @Override
    @PostMapping("/GetTrialList")
    public PageListVO getTrialList(@RequestBody PaginationFlowTask pagination) {
        List<FlowTaskListModel> result = flowTaskService.getTrialList(pagination);
        PageListVO pageListVO = new PageListVO();
        pageListVO.setList(result);
        pageListVO.setPagination(JsonUtil.getJsonToBean(pagination,PaginationVO.class));
        return pageListVO;
    }

    /**
     * 列表（订单状态）
     *
     * @return
     */
    @Override
    @PostMapping("/GetOrderStaList")
    public List<FlowTaskEntity> getOrderStaList(@RequestBody List<String> id) {
        return flowTaskService.getOrderStaList(id);
    }

    @Override
    @PostMapping("/GetTaskList")
    public List<FlowTaskEntity> getTaskList(String[] ids) {
        return flowTaskService.getInfosSubmit(ids, FlowTaskEntity::getStatus, FlowTaskEntity::getId, FlowTaskEntity::getProcessId);
    }

    @Override
    @GetMapping("/getDelegateList")
    public List<FlowDelegateEntity> getDelegateList() {
        return flowDelegateService.getList();
    }

    @Override
    @PostMapping("/getCirculateList")
    public PageListVO getCirculateList(@RequestBody PaginationFlowTask pagination) {
        List<FlowTaskListModel> result = flowTaskService.getCirculateList(pagination);
        PageListVO pageListVO = new PageListVO();
        pageListVO.setList(result);
        pageListVO.setPagination(JsonUtil.getJsonToBean(pagination,PaginationVO.class));
        return pageListVO;
    }

    //———————————————流程引擎数据——————————

    @Override
    @PostMapping(value = "/getListAll")
    public PageListVO getListAll(@RequestBody FlowPagination pagination) {
        List<FlowTemplateEntity> pageList = flowTemplateService.getListAll(pagination, true);
        PageListVO pageListVO = new PageListVO();
        pageListVO.setList(pageList);
        pageListVO.setPagination(JsonUtil.getJsonToBean(pagination,PaginationVO.class));
        return pageListVO;
    }

    @Override
    @PostMapping("/getTemplateList")
    public List<FlowTemplateEntity> getTemplateList(@RequestBody List<String> templaIdList) {
        List<FlowTemplateEntity> list = flowTemplateService.getTemplateList(templaIdList);
        return list;
    }

    @Override
    @GetMapping("/getFlowTemplateJsonEntity")
    public FlowTemplateJsonEntity getFlowTemplateJsonEntity(@RequestParam("id") String id) throws WorkFlowException {
        return flowTemplateJsonService.getInfo(id);
    }

    @Override
    @GetMapping("/getInfoSubmit")
    public ActionResult<FlowTaskEntity> getInfoSubmit(@RequestParam("id") String id) {
        ActionResult result = new ActionResult();
        try {
            FlowTaskEntity info = flowTaskService.getInfo(id);
            result.setData(info);
        } catch (Exception e) {
        }
        return result;
    }

    @Override
    @PostMapping("/deleteFlowTask")
    public ActionResult deleteFlowTask(@RequestBody FlowTaskEntity taskEntity) {
        try{
            flowTaskService.delete(taskEntity);
            return  ActionResult.success();
        }catch (Exception e){
            return  ActionResult.fail(e.getMessage());
        }
    }

    @Override
    @PostMapping("/createTemplate")
    public ActionResult createTemplate(@RequestBody FlowTemplateCrForm form) {
        String msg = "";
        try {
            if (flowTemplateService.isExistByFullName(form.getFullName(), form.getId())) {
                return ActionResult.fail(MsgCode.EXIST001.get());
            }
            if (flowTemplateService.isExistByEnCode(form.getEnCode(), form.getId())) {
                return ActionResult.fail(MsgCode.EXIST002.get());
            }
            FlowTemplateEntity entity = JsonUtil.getJsonToBean(form, FlowTemplateEntity.class);
            flowTemplateService.create(entity);
        } catch (Exception e) {
            msg = e.getMessage();
        }
        return StringUtil.isNotEmpty(msg) ? ActionResult.fail(msg) : ActionResult.success();
    }

    @Override
    @PostMapping("/updateTemplate/{id}")
    public ActionResult updateTemplate(@PathVariable("id") String id, @RequestBody FlowTemplateCrForm form) {
        String msg = "";
        try {
            if (flowTemplateService.isExistByFullName(form.getFullName(), id)) {
                ActionResult.success(MsgCode.EXIST001.get());
            }
            if (flowTemplateService.isExistByEnCode(form.getEnCode(),id)) {
                ActionResult.success(MsgCode.EXIST002.get());
            }
            FlowTemplateEntity entity = JsonUtil.getJsonToBean(form, FlowTemplateEntity.class);
            flowTemplateService.update(id, entity);
        } catch (Exception e) {
            msg = e.getMessage();
        }
        return StringUtil.isNotEmpty(msg) ? ActionResult.fail(msg) : ActionResult.success();
    }

    @Override
    @GetMapping("/getTemplateInfo/{id}")
    public FlowTemplateInfoVO getTemplateInfo(@PathVariable("id") String id) {
        FlowTemplateInfoVO vo = new FlowTemplateInfoVO();
        try {
            vo = flowTemplateService.info(id);
        } catch (Exception e) {
            vo = null;
        }
        return vo;
    }

    @Override
    @GetMapping("/deleteTemplateInfo/{id}")
    public ActionResult deleteTemplateInfo(@PathVariable("id") String id) {
        String msg = "";
        try {
            FlowTemplateEntity entity = flowTemplateService.getInfo(id);
            flowTemplateService.delete(entity);
        } catch (Exception e) {
            msg = e.getMessage();
        }
        return StringUtil.isNotEmpty(msg) ? ActionResult.fail(msg) : ActionResult.success();
    }

    /**
     * 逻辑删除还原数据
     * @param id
     */
    @Override
    @GetMapping("/saveLogicFlowAndForm" )
    public void saveLogicFlowAndForm(@RequestParam("id" ) String id) {
        flowTemplateService.saveLogicFlowAndForm(id);
    }

    /**
     * 获取待办及负责流程
     */
    @Override
    @GetMapping("/flowWork" )
    public FlowWorkListVO flowWork(@RequestParam("fromId") String fromId) {
        return flowTaskService.flowWork(fromId);
    }

    /**
     * 获取待办及负责流程
     */
    @Override
    @PostMapping("/saveFlowWork" )
    public boolean saveFlowWork(@RequestBody WorkHandoverModel workHandoverModel) {
        return flowTaskService.flowWork(workHandoverModel);
    }

    @Override
    @PostMapping("/batchCreateOrUpdate")
    public ActionResult batchCreateOrUpdate(@RequestBody FlowModel flowModel)  {
        ActionResult result = new ActionResult();
        try {
            flowDynamicService.batchCreateOrUpdate(flowModel);
        }catch (Exception e){
            result.setCode(400);
            result.setMsg(e.getMessage());
        }
        return result;
    }


    @Override
    @PostMapping("/pushmessage")
    public ActionResult  List2( @RequestBody   PaginationFlowTask paginationFlowTask) {
       String  category="1";
        List<FlowTaskListModel> data = new ArrayList<>();
        paginationFlowTask.setDelegateType(true);
        if (FlowNature.WAIT.equals(category)) {
            data.addAll(flowTaskService.getWaitList(paginationFlowTask));
        }
        List<FlowBeforeListVO> listVO = new LinkedList<>();
        List<UserEntity> userList = serviceUtil.getUserName(data.stream().map(FlowTaskListModel::getCreatorUserId).collect(Collectors.toList()));
        boolean isBatch = FlowNature.BATCH.equals(category);
        List<FlowTaskNodeEntity> taskNodeList = new ArrayList<>();
        List<String> taskNodeIdList = data.stream().map(FlowTaskListModel::getThisStepId).collect(Collectors.toList());
        if (isBatch) {
            taskNodeList.addAll(flowTaskNodeService.getList(taskNodeIdList, FlowTaskNodeEntity::getId, FlowTaskNodeEntity::getNodePropertyJson));
        }
        for (FlowTaskListModel task : data) {
            FlowBeforeListVO vo = JsonUtil.getJsonToBean(task, FlowBeforeListVO.class);
            //用户名称赋值
            UserEntity user = userList.stream().filter(t -> t.getId().equals(vo.getCreatorUserId())).findFirst().orElse(null);
            vo.setUserName(user != null ? user.getRealName() + "/" + user.getAccount() : "");
            FlowTaskNodeEntity taskNode = taskNodeList.stream().filter(t -> t.getId().equals(task.getThisStepId())).findFirst().orElse(null);
            if (isBatch && taskNode != null) {
                ChildNodeList childNode = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
                vo.setApproversProperties(JsonUtil.getObjectToString(childNode.getProperties()));
            }
            vo.setFlowVersion(StringUtil.isEmpty(vo.getFlowVersion()) ? "" : vo.getFlowVersion());

            //  根据     flowId     processId   获取流程 节点的处理人
            String thisStepId = vo.getThisStepId();     // f_task_node_id
            String processId = vo.getProcessId();  //  f_task_id

            QueryWrapper<FlowTaskOperatorEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(FlowTaskOperatorEntity::getTaskNodeId, thisStepId);
            queryWrapper.lambda().eq(FlowTaskOperatorEntity::getTaskId, processId);
            queryWrapper.lambda().orderByDesc(FlowTaskOperatorEntity::getCreatorTime);

            List<FlowTaskOperatorEntity> list = this.flowTaskOperatorService.list(queryWrapper);
            if(CollectionUtil.isNotEmpty(list)){
                for (FlowTaskOperatorEntity flowTaskOperatorEntity:list
                ) {
                    String handleId = flowTaskOperatorEntity.getHandleId();
                    String mobilePhone = userApi.getInfoById(handleId).getMobilePhone();
                    vo.setAssigneMObile(mobilePhone);
                }

            }


            if(vo.getAssigneMObile()!=null){
                flowTaskMessageService.saveList(vo);
            }


        }





        return ActionResult.success();
    }


}
